#include "videowidget.h"
#include <QPainter>
#include "xffmpeg.h"
#include <QDebug>
#include "qvideothread.h"

VideoWidget::VideoWidget(QWidget* p):QOpenGLWidget(p)
{
    //XFFmpeg::Get()->Open("test.mp4");
    startTimer(20);
    QVideoThread::Get()->start();
}

VideoWidget::~VideoWidget()
{
    QVideoThread::Get()->end();
    QVideoThread::Get()->wait();
}



void VideoWidget::paintEvent(QPaintEvent *e)
{
    static QImage* image = NULL;
    static int w = 0;
    static int h = 0;
    if(w != width() || h != height())
    {
        if(image)
        {
            delete image->bits();
            delete image;
            image = NULL;
        }
    }
    if(image == NULL)
    {
        uchar *buf = new uchar[width() * height() * 4];
        image = new QImage(buf, width(), height(), QImage::Format_ARGB32);
    }
//    AVPacket pkt = XFFmpeg::Get()->Read();
//    if(pkt.stream_index != XFFmpeg::Get()->GetVideoStream())
//    {
//        return;
//    }
//    if(pkt.size == 0) return;
//    AVFrame *yuv = XFFmpeg::Get()->Decode(pkt, NULL);

//    av_packet_unref(&pkt);
//    if(yuv == NULL) return;
    bool bRet = XFFmpeg::Get()->ToRGB((char*)image->bits(), width(), height());
    if(!bRet)
        return;

    QPainter painter;
    painter.begin(this);
    painter.drawImage(QPoint(0, 0), *image);
    painter.end();
}

void VideoWidget::timerEvent(QTimerEvent *e)
{
    this->update();
}
